//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-09-04  Jed Young  Creation
//

using chunmapModel
using chunmapData
using gfx2
using gfx
using gfx2Imp
using web
using chunmapView
using chunmapRaster

**
** GService
**
const class GService : WebMod
{
  const Unsafe layers
  const ImageCache cache

  new make(LayerList list)
  {
    layers = Unsafe(list)
    this.cache = ImageCache.create
  }

  override Void onService()
  {
    Int x:=0
    Int y:=0
    Int z:=0
    try
    {
      querys := req.uri.query
      x = querys["x"].toInt
      y = querys["y"].toInt
      z = querys["z"].toInt
    }catch{}

    image := getImage(x, y, z)

    type := MimeType.forExt("png")
    res.headers["Content-Type"] = type.toStr
    image.save(res.out, type)
  }

  Image2 getImage(Int x, Int y, Int z)
  {
    tile := Tile(x, y, z)
    name := tile.toStr

    //try get cache
    image := cache.get(name)
    if(image != null) return image

    //using AWT
    Gfx2.setEngine("AWT")

    // renderMap
    map := CMap(Size(GEncode.tileSize, GEncode.tileSize))
    map.layers = layers.val

    map.view.setViewEnvelope(GEncode.getEnvelope(tile))
    //map.fullView
    map.render
    image = map.image

    cache.set(name, image)

    return image
  }
}